<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Request;

// 玩家 根据游戏角色  新增 流失用户统计 只与昨日对比
class EMail extends  Model{

	//protected $table='email';
    //protected $_db_select = 'mysql';

    public $timestamps = true;

    const DB_FIELDS = 'id,title,content,start_time,end_time,receive_method,receiver,area_list,gold,diamond,is_prop,prop,add_time,send_time,ticket';

    public static $send_mail_type =  [1 => 'single player', 2 => 'many player', 3=> 'all player', 4 => 'online player'];
    
	public function paginate()
    {
    	$perPage = Request::get('per_page', 15);
        $page = Request::get('page', 1);

        $start = ($page-1)*$perPage;

        $rw = \DB::connection($this->selectdb())->table('email')->where('deleted_at', 0)->orderBy("id", 'desc')->skip($start)->take($perPage);
        self::SourceCondition($rw);
        $data = $rw->get();
        $data = $data->toArray();

        $total = \DB::connection($this->selectdb())->table('email')->where('deleted_at', 0)->get()->count();

        //$data = json_decode($data, true);
        // var_dump($data);
        // exit;

        $list = static::hydrate($data);

        $paginator = new LengthAwarePaginator($list, $total, $perPage);

        $paginator->setPath(url()->current());

        return $paginator;
    }

    public static function with($relations)
    {
        return new static;
    }

    public function selectdb($select = ''){
        return 'mysql';
    }

    public function getConnectionName(){
        return $this->selectdb();
    }
    public function getTable($table = ''){
    
        if ( !$table ){
            return 'email';
        }
        if ($table) {

            $this->table = $table;
        }

        return $this->table;
    }


    public static function assignByOut(&$one, $out){
        $flds = explode(',', self::DB_FIELDS);
        
        foreach ($flds as $fld) {
            isset($out[$fld]) && $one->{$fld} = $out[$fld];
            if ($fld == 'prop'){
                if (is_string($one->{$fld})){
                    $one->{$fld} = (json_decode($one->{$fld}, true));
                } 
                if (is_array($one->{$fld})){
                    $one->{$fld} = array_values($one->{$fld});
                    $one->{$fld} = json_encode($one->{$fld});
                }
            }
        }

        if (is_array($one->area_list)) {
            $one->area_list = implode(",", $one->area_list);
        }
    }


    public function fromDateTime($value){
        return strtotime(parent::fromDateTime($value));
    }

    // 发送邮件
    public static function send($one){

        if (!$one->area_list) {
            $area_list = \App\Models\Area::areaAll();
            foreach ($area_list as $area_obj) {
                $one->area_list = $area_obj->areaId;
                self::sendMail($one);
            }
            return ;
        }
        
        self::sendMail($one);
    }

    public static function sendMail($one) {
        switch ($one->receive_method){
            case 1:
            case 2:
            case 3:
            case 4:
                $one->receiver = json_decode($one->receiver , true);
                $playerId = is_array($one->receiver) ? $one->receiver[0] : $one->receiver;
                $area_id = (int)$one->area_list;
                if (is_string($one->prop)) {
                    $one->prop = json_decode($one->prop);
                }
                self::sendByPlayerId($one, $playerId, $area_id);
                break;
            }
    }

    protected static function sendByPlayerId($one, $playerId, $area_id){

        \App\Models\SendSocketToGame::SendAction(function($socket)use($one, $playerId, $area_id){
            $data['msgid'] = \App\Service\MessageDef::http_send_mail_req;
            $data["cp_area"] = intval($area_id); 
            $data["title"] = $one->title;
            $data["content"] = $one->content;
            $data["playerId"] = $playerId;
            $data["item"] = $one->prop;
            $data["money"] = ["gold"=>$one->gold ?:0, "diamond" => $one->diamond?:0, "ticket"=> $one->ticket];
            $data["receive_method"] = $one->receive_method;
            $data["player_ids"] = $one->receiver;
            $ret = $socket->send($data);
            \Log::debug('send single player mail'. json_encode($data) );

            $read_data = $socket->ReadHttpReponse();
            \Log::debug('read mail reponse data', [$read_data]);
        });
    }

    //批量发送邮件
    protected static function MutilSendMail($one, $playerIds, $area_id)
    {
        \App\Models\SendSocketToGame::SendAction(function($socket)use($one, $playerId, $area_id){
       
            foreach($playerIds as $playerId){
                $data['msgid'] = \App\Service\MessageDef::http_send_mail_req;
                $data["cp_area"] = intval($area_id); 
                $data["title"] = $one->title;
                $data["content"] = $one->content;
                $data["playerId"] = $playerId;
                $data["item"] = $one->prop;
                $data["money"] = ["gold"=>$one->gold ?:0, "diamond" => $one->diamond?:0];

                $ret = $socket->send($data);
            }
        });
    }

    public static function SourceCondition(&$rw)
    {
        $cond = Request::all();
        if ($cond['title']){
            $rw->where("title", 'like', $cond["title"].'%');
        }
        if ($cond["area_list"] or $cond['area']){
            $rw->where("area_list", $cond['area_list'] ?: $cond['area']);
        }

        if (isset($cond["send_time"])){
            $send_time = $cond['send_time'];
            (0 == $send_time) && $rw->where('send_time', 0);
        }
    }
}
